package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;

import com.ruoyi.health.domain.User;
import com.ruoyi.health.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Description : 前台用户验证处理
 *                从user表中取前台用户信息
 * @Author : libin
 * @Date : 2023-08-17
 */
@Service("userDetailsServiceImpl")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private IUserService userService;

    @Autowired
    private UserPasswordService userPasswordService;

    //前台用户的【loadUserByUsername】是根据【手机号】登录
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取前台用户user
        User user = userService.selectUserByPhone(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户(手机号)：{} 不存在.", username);
            throw new ServiceException("登录用户(手机号)：" + username + " 不存在");
        }

        // user中携带了 username和password信息,此处是【验证密码】
        userPasswordService.validate(user);
        // //身份权限名可以自定义，按照这里写比较规范
        //  AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN")
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(User user) {

        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getId());
        sysUser.setUserName(user.getPhone());
        LoginUser loginUser = new LoginUser(user.getId(),null,sysUser,null);
        //将User 封装为 Sys_user

        return loginUser;
    }
}